using System;
using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Web.UI.HtmlControls;


namespace Library.WebControls.SimplePopup {

	[ControlBuilder(typeof(PlaceHolderControlBuilder))]
	[ToolboxBitmap(typeof(SpPopup), "Library.WebControls.SimplePopup.SpPopup.bmp")]
	
	
	[DefaultProperty("PopupContent")]
	[Designer(typeof(SpPopupDesign))]
	[DesignTimeVisible(true)]
	public class SpPopup : BaseAjaxControl, IEffectControl {

		public SpPopup() {
			CssFileName = BaseCssDir + "sppup-ui.css";
			TimeEffect = 5;
			StepEffect = 1;

			ClientScript = new ClientScript();
			ContentRenderMode = ContentRenderMode.Normal;
			PopupPosition = PopupPosition.CenterScreen;
			CloseType = CloseAction.Button;

		}

		private bool _isCallback;
		public override bool IsCallback {
			get {
				return _isCallback;
			}
		}
		[PersistenceMode(PersistenceMode.InnerProperty)]
		[MergableProperty(false)]
		[Category("Data")]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
		[DefaultValue("")]
		public ClientScript ClientScript {
			private set;
			get;
		}

		public CloseAction CloseType { get; set; }

		public Unit Width {
			get {
				EnsureChildControls();
				return new Unit(_divPopup.Style[HtmlTextWriterStyle.Width]);
			}
			set {
				EnsureChildControls();
				_divPopup.Style[HtmlTextWriterStyle.Width] = value.ToString();
			}
		}


		public Unit Height {
			get {
				EnsureChildControls();
				return new Unit(_divPopup.Style[HtmlTextWriterStyle.Height]);
			}
			set {
				EnsureChildControls();
				_divPopup.Style[HtmlTextWriterStyle.Height] = value.ToString();
			}
		}

		private bool _enableDrafDrop;
		public bool EnableDrafDrop {
			get { return _enableDrafDrop; }
			set { _enableDrafDrop = value; }
		}



		private Literal _lblText;
		public string TitleText {
			get {
				EnsureChildControls();
				return _lblText.Text;
			}
			set {
				EnsureChildControls();
				_lblText.Text = value;
			}
		}
		public static bool IsSpPopupCallback(Page page) {
			return !String.IsNullOrEmpty(page.Request[SpPopupControlCallbackServerId]);
		}

		protected const string SpPopupControlCallbackServerId = "__SPPOPUPRQSID_";
		protected override void OnInit(EventArgs e) {
			base.OnInit(e);
			if (Request != null) {
				_isCallback = IsSpPopupCallback(Page) && Request[SpPopupControlCallbackServerId] == ClientID;
			} else {
				_isCallback = false;
			}
		}
		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);
			if (IncludeScriptOnLoad(typeof(SpPopup), "SPPopup", "Library.WebControls.SimplePopup.include.SpPopup.js", UtilLib, EffectLib)) {

			}
			if (_enableDrafDrop) {
				IncludeJavascriptCore(DragDropLib);
			}
			if (IsCallback) {
				OnCustomCallback(new CustomCallbackEventArgs(String.Empty));
			}
		}

		public string ShowAtControl { get; set; }

		public bool ModelMode { get; set; }

		private bool _showCloseButton = true;
		public bool ShowCloseButton {
			get { return _showCloseButton; }
			set { _showCloseButton = value; }
		}

		private string _closeButtonHoverText;
		public string CloseButtonHoverText {
			get {
				if (_closeButtonHoverText == null) return String.Empty;
				return _closeButtonHoverText;
			}
			set { _closeButtonHoverText = value; }
		}


		public PopupPosition PopupPosition { get; set; }
		private HtmlGenericControl _divPopup;
		private WebControl _popupTitleText;
		[Description("Popup title")]
		[PersistenceMode(PersistenceMode.InnerProperty)]
		[MergableProperty(false)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
		[DefaultValue("")]
		public WebControl PoupTitleText {
			get {
				EnsureChildControls();
				return _popupTitleText;
			}
		}
		private HtmlGenericControl _popupContent;

		[PersistenceMode(PersistenceMode.InnerProperty)]
		[MergableProperty(false)]


		public HtmlGenericControl PopupContent {
			get {
				EnsureChildControls();
				return _popupContent;
			}
		}

		private HtmlGenericControl _divTitle;
		private HtmlGenericControl _divClosebutton;
		protected override void CreateChildControls() {
			Controls.Clear();
			_divPopup = new HtmlGenericNaming("div");
			_divPopup.Attributes["class"] = "sppup";
			_divTitle = new HtmlGenericControl("div");
			_divPopup.Controls.Add(_divTitle);
			_divTitle.Attributes["class"] = "putitle";
			_lblText = new Literal { Text = "Title" };
			_popupTitleText = new WebControl(HtmlTextWriterTag.Div);
			_popupTitleText.Controls.Add(_lblText);
			_popupTitleText.CssClass = "putitleText";
			_divTitle.Controls.Add(_popupTitleText);
			_divClosebutton = new HtmlGenericControl("div");
			_divClosebutton.Attributes["class"] = "puclosebutton";
			_divTitle.Controls.Add(_divClosebutton);

			_popupContent = new HtmlGenericControl("div");
			_popupContent.Attributes["class"] = "pucontent";
			_divPopup.Controls.Add(_popupContent);

			Controls.Add(_divPopup);
		}

		public bool ShowTitle {
			get {
				EnsureChildControls();
				return _divTitle.Visible;
			}
			set {
				EnsureChildControls();
				_divTitle.Visible = value;
			}

		}


		public override string ID {
			get {
				EnsureChildControls();
				return _divPopup.ID;
			}
			set {
				EnsureChildControls();
				_divPopup.ID = value;
				_divTitle.ID = value + "_T";
			}
		}

		public override string ClientID {
			get {
				EnsureChildControls();
				return _divPopup.ClientID;
			}
		}
		protected override void CreateClientObjectAtRender(HtmlTextWriter writer) {
			BeginScriptTag(writer);
			writer.Write("var {0}=new SpPopup();", ClientName);
			string ownerId = String.Empty;
			if (!String.IsNullOrEmpty(ShowAtControl)) {
				bool isServerControl = false;
				Control ctr = Page.FindControl(ShowAtControl);
				if (ctr != null) {
					ownerId = ctr.ClientID;
					isServerControl = true;
					//break;
				}
				//foreach (Control ctr in Page.Controls) {
				//  if (ctr.ID == ShowAtControl) {


				//  }
				//}

				if (!isServerControl) {
					ownerId = ShowAtControl;
				}
			}

			writer.Write("{0}.Init('{1}','{0}','{2}',{3},'{4}',{5},{6},'{7}',{8},{9},'{10}',{11});", ClientName, ClientID, ownerId, ModelMode.ToString().ToLower(), (Int32)DisplayEffect, TimeEffect, StepEffect, _divTitle.ClientID, (Int32)ContentRenderMode, (Int32)PopupPosition, _divTitle.ClientID, (Int32)CloseType);
			if (_enableDrafDrop) {
				writer.Write(String.Format("Library.WebControl.DragDrop.Register('{0}','{1}', false);", _divTitle.ClientID, ClientID));
			}

			AddScriptHandler(writer, 1, ClientScript.Shown, "AddHandler");
			AddScriptHandler(writer, 2, ClientScript.Hidden, "AddHandler");
			AddScriptHandler(writer, 3, ClientScript.BeforeCallback, "AddHandler");
			
			EndScriptTag(writer);
		}
		protected override void Render(HtmlTextWriter writer) {
			if (Visible) {
				if (ShowCloseButton) {
					_divClosebutton.Attributes["title"] = CloseButtonHoverText;
					_divClosebutton.Attributes["onclick"] = ClientName + ".Hide();";
				} else {
					_divClosebutton.Visible = false;
				}

				if (!IsCallback) {
					if (ContentRenderMode != ContentRenderMode.Normal) {
						_popupContent.Visible = false;
					}
					base.Render(writer);
				} else {
					WriteCustomCallbackCompleteResult();
					foreach (Control control in _popupContent.Controls) {
						control.RenderControl(writer);
					}
					FlushAndEndCallback();
				}
			}
		}

		public event CustomCallbackEventHandler CustomCallback;

		protected virtual void OnCustomCallback(CustomCallbackEventArgs e) {
			var handler = CustomCallback;
			if (handler != null) {
				try {
					handler(this, e);
					ProcessCustomCallbackEventArgs(e);
				} catch (Exception ex) {
					WriteError(ex);
				}
			}
		}

		public Effect DisplayEffect { get; set; }

		public int TimeEffect {
			get;
			set;
		}

		public int StepEffect {
			get;
			set;
		}

		public ContentRenderMode ContentRenderMode { get; set; }

	}
}
